package com.helin.helinhealth.controller;

import com.helin.helinhealth.common.Result;
import com.helin.helinhealth.entity.ExportTask;
import com.helin.helinhealth.service.FileExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * 文件导出控制器
 * 
 * <p>
 * 该控制器提供文件导出的API接口，支持直接下载已生成的导出文件。
 * </p>
 */
@Slf4j
@Tag(name = "文件导出", description = "文件导出相关接口")
@RestController
@RequestMapping("/api/file-export")
public class FileExportController {

    @Autowired
    private FileExportService fileExportService;

    @Operation(summary = "生成导出文件", description = "根据导出任务生成文件")
    @PostMapping("/generate")
    public Result generateFile(@RequestBody ExportTask task) {
        log.info("开始生成导出文件: {}", task);
        try {
            String filePath = fileExportService.generateExportFile(task);
            return Result.success("文件生成成功", filePath);
        } catch (Exception e) {
            log.error("文件生成失败", e);
            return Result.error("文件生成失败: " + e.getMessage());
        }
    }

    @Operation(summary = "下载导出文件", description = "下载指定路径的导出文件")
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(
            @Parameter(description = "文件路径") 
            @RequestParam String filePath) {
        log.info("下载文件: {}", filePath);
        
        try {
            byte[] fileContent = fileExportService.getExportFileContent(filePath);
            
            // 从文件路径中提取文件名
            String fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
            
            // 设置Content-Type
            MediaType mediaType;
            if (fileName.endsWith(".xlsx")) {
                mediaType = MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            } else if (fileName.endsWith(".pdf")) {
                mediaType = MediaType.APPLICATION_PDF;
            } else if (fileName.endsWith(".csv")) {
                mediaType = MediaType.parseMediaType("text/csv");
            } else {
                mediaType = MediaType.APPLICATION_OCTET_STREAM;
            }
            
            ByteArrayResource resource = new ByteArrayResource(fileContent);
            
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .contentType(mediaType)
                    .contentLength(fileContent.length)
                    .body(resource);
        } catch (Exception e) {
            log.error("文件下载失败", e);
            return ResponseEntity.notFound().build();
        }
    }
} 